<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择退货仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="openDepotWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-supplierName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择供应商"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品
              </el-button>
            </template>

            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品
              </el-button>
            </template>

            <template v-slot:filter-scanCode>
              <div class="scan-input-box">
                <ScanInputBox
                  v-model:query="scanInfo.query"
                  :api="scanInfo.api"
                  :disabled="!canAddProduct"
                  @callback="onCallBackScanData"
                />
              </div>
            </template>
          </NewPageFilter>

          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber }}</p>
                  <p>{{ scope.row.brandName }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName }}</p>
                  <p>{{ scope.row.productCode }}</p>
                  <p>{{ scope.row.alias }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue }}</p>
                  <p>{{ scope.row.codeTypeValue }}</p>
                  <p>{{ scope.row.productCategoryValue }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard }}</p>
                  <p>{{ scope.row.unitName }}</p>
                </template>
                <template v-slot:col-reasonValue="scope">
                  <el-form-item
                    class="margin-bottom"
                    :prop="`data.${scope.$index}.reason`"
                  >
                    <SelectModel
                      v-model.lazy="scope.row.reason"
                      style="margintop: 18px"
                      type-code="purch_return_reason"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-qty="scope">
                  <template v-if="!tableInfo.isSysGroup">
                    <el-form-item
                      class="margin-bottom"
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="PageTable-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="PageTable-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="PageTable-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span
                      v-else-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                    >
                  </template>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
                <template v-slot:col-receiptNumber="scope">
                  <el-input
                    v-if="scope.row.isConsignBusiness != 1"
                    v-model="scope.row.receiptNumber"
                    :maxlength="50"
                  ></el-input>
                  <span v-else>{{ scope.row.receiptNumber || '-' }}</span>
                </template>
                <template v-slot:col-receiptPrice="scope">
                  <el-form-item
                    v-if="scope.row.isConsignBusiness != 1"
                    :prop="`data.${scope.$index}[receiptPrice]`"
                  >
                    <el-input-number
                      v-model="scope.row.receiptPrice"
                      controls-position="right"
                      style="minwidth: 100px; margintop: 18px"
                      :precision="systemConfig.price_precision"
                      :step="1"
                      :min="0"
                      :max="999999999999999"
                      @change="
                        changePrice($event, `data.${scope.$index}.receiptPrice`)
                      "
                    />
                  </el-form-item>
                  <span v-else>{{ scope.row.receiptPrice || '-' }}</span>
                </template>
                <template v-slot:col-receiptCalcQty="scope">
                  <el-form-item
                    v-if="scope.row.isConsignBusiness != 1"
                    :prop="`data.${scope.$index}.receiptCalcQty`"
                  >
                    <el-input-number
                      v-model.lazy="scope.row.receiptCalcQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.qty_show_precision"
                      :min="0"
                      :max="scope.row.qty"
                    />
                  </el-form-item>
                  <span v-else>{{ scope.row.receiptCalcQty || '-' }}</span>
                </template>
              </PageTable>
            </el-form>
          </div>

          <!-- 选择产品 -->
          <SelectDepotStorage
            v-if="selectDepotStorageInfo.visible"
            v-model:showDialog="selectDepotStorageInfo.visible"
            v-model:query="selectDepotStorageInfo.query"
            :leftTableKey="selectDepotStorageInfo.leftTableKey"
            :rightTableKey="selectDepotStorageInfo.rightTableKey"
            :excludeQueryList="selectDepotStorageInfo.excludeQueryList"
            :showPrice="$permission('purchReturn:price')"
            @callback="selectDepotStorageCallBack"
          ></SelectDepotStorage>
          <!--           在供货目录中 根据产品选择供应商 -->
          <SelectSupplier
            v-if="selectProductSupplier.visible"
            v-model:show-dialog="selectProductSupplier.visible"
            v-model:query="selectProductSupplier.query"
            :check-box="false"
            :highlight-row="true"
            :api="selectProductSupplier.api"
            @callback="selectSupplierCallback"
          />
          <SelectDepot
            v-if="depotInfo.visible"
            v-model:showDialog="depotInfo.visible"
            :checkBox="false"
            v-model:query="depotInfo.query"
            :highlightRow="true"
            :saveEmpty="true"
            @callback="selectDepotCallBack"
          />
          <SelectBatchNumber
            v-if="batchNumberInfo.visible"
            v-model:show-dialog="batchNumberInfo.visible"
            v-model:query="batchNumberInfo.query"
            @callback="selectBatchNumberCallback"
          ></SelectBatchNumber>
        </div>
      </div>
    </NewFullScreen>
    <select-order
      v-if="dialogInfo.visible"
      v-model:show-dialog="dialogInfo.visible"
      v-model:query="dialogInfo.query"
      @callback="selectOrderCallback"
    ></select-order>
    <!-- 个体操作 -->
    <select-individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:leftQueryObj="individualInfo.leftQuery"
      v-model:rightQueryObj="individualInfo.rightQuery"
      v-model:infoList="individualInfo.productInfo"
      :requestRightList="!!purchReturnId"
      v-model:rightApi="individualInfo.rightApi"
      v-model:leftApi="individualInfo.leftApi"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :leftQueryParams="individualInfo.leftQueryParams"
      v-model:rightVo="individualInfo.rightVo"
      :showPrice="$permission('purchReturn:price')"
      :scanInfo="scanInfo"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
  </div>
  <SelectContract
    v-if="contractInfo.visible"
    v-model:showDialog="contractInfo.visible"
    :checkBox="false"
    :query="contractInfo.query"
    :data="contractInfo.data"
    :changeContract="contractInfo.changeContract"
    :highlightRow="true"
    :saveEmpty="true"
    @callback="selectContractCallBack"
  />
</template>

<script setup name="purchReturnModify">
import moment from 'moment'
import { getDepotStockCustomizeListPage } from '@/api/stock'
import selectIndividual from './components/individual'
import _ from 'lodash'
import {
  detailPurchReturn,
  purchReturnDetailsCustomizeListAll,
  getPurchApplicationDetailAll,
  updatePurchReturnOrder,
  createPurchReturnOrder,
  getPurchReturnOrderDetail,
} from '@/api/purch'
import { getCoreSystemConfigAll } from '@/api/core'
import { getSupplierPage } from '@/api/core'
import { depotStockCustomizeScan } from '@/api/stock'
import ScanInputBox from './components/ScanInputBox'
import SelectOrder from './selectOrder'
import { getCustomizeSetting } from '@/api/customize'
import SelectContract from './selectContract'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  tableRow: {
    type: Object,
    default: () => {
      return {}
    },
  },
  purchReturnId: {
    type: [Number, String],
  },
  purchAccording: {
    type: [Number, String],
  },
})
const scanInfo = ref({
  api: depotStockCustomizeScan,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            '1'
          ) !== -1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ''
        : '',
      supplierId: '',
      // validateExpire: false
    },
  },
})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
    // receiveAddressValue:'',
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    supplierName: proxy.$store.state.user.userInfo.supplierName
      ? proxy.$store.state.user.userInfo.supplierName.name
      : '',
    supplierId: proxy.$store.state.user.userInfo.supplierName
      ? proxy.$store.state.user.userInfo.supplierName.id
      : '',
    purchAccording:
      props.purchAccording ||
      proxy.$store.state.permission.systemConfig.purch_according,
  },
  fieldList: [
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '退货仓库', value: 'depotName', type: 'slot' },
    { label: '部门', value: 'deptName', type: 'input', disabled: true },

    {
      label: '采购退货类型',
      value: 'returnType',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'purch_return_type',
    },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '退货联系人', value: 'contact', type: 'input' },
    { label: '联系人电话', value: 'phone', type: 'input' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show:
        props.purchReturnId &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '采购依据',
      value: 'purchAccording',
      type: 'select-model',
      code: 'purch_according',
      disabled: true,
    },
    // {label: '收货地址', value: 'receiveAddressValue', type: 'slot'},
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    // receiveAddressValue:[{required : true, message: '请选择收货地址', target: 'change'}],
    deptName: [{ required: true, message: '请输入部门', trigger: 'blur' }],
    returnType: [
      {
        required: true,
        message: '请选择采购退货类型',
        target: 'change',
      },
    ],
    depotName: [{ required: true, message: '请选择仓库', target: 'change' }],
    supplierName: [
      { required: true, message: '请选择供应商', target: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'change,blur' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    // { type: "button", label: "领用退回单导入", event: getUseReturnList },
    {
      type: 'slot',
      value: 'removeProduct',
    },
    { type: 'slot', value: 'scanCode' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '个体操作',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '切换合同',
        event: changeContract,
        show: true,
        // ifRender: function (row) {
        //   return row.contractVOList && row.contractVOList.length > 1;
        // },
      },
      { label: '删除产品', event: removeProduct, show: true },
    ],
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const selectSupplierInfo = ref({
  visible: false,
  query: {
    supplierAuth: 'supplierId',
  },
})
//在供货目录中 根据产品id选择供应商
const selectProductSupplier = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    supplierAuth: 'supplierId',
  },
})
const index = ref('')
const selectReceiveAddressInfo = ref({
  visible: false,
  query: {},
})
const contractInfo = ref({
  visible: false,
  changeContract: false,
  query: {},
  data: [],
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const depotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: '1',
    useTypeId: '1',
    isCargoSpaceManage: 0,
  },
})
const dialogInfo = ref({
  visible: false,
  query: {
    status: 'complete',
    type: 'useReturn',
    sort: 'create_time desc',
    storageDepotAuth: true,
  },
})
const selectDepotStorageInfo = ref({
  //库存产品
  leftTableKey:
    'productPurchReturnPageWithDepotStockLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'productPurchReturnPageWithDepotStockRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    supplierId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
    queryParams: {
      purchAccording:
        props.purchAccording ||
        proxy.$store.state.permission.systemConfig.purch_according,
    },
  },
})
const supplierInfo = ref({
  visible: false,
  query: {
    productId: '',
    supplierIdNotIn: '',
  },
})
const individualInfo = ref({
  //个体操作
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  leftQueryParams: {
    purchAccording:
      props.purchAccording ||
      proxy.$store.state.permission.systemConfig.purch_according,
  },
  rightApi: purchReturnDetailsCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
  leftTableKey:
    'productPurchReturnPageWithDepotStockRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'purchPurchReturnModifySingle-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
})
const isActive = ref(false)
const batchNumberInfo = ref({
  visible: false,
  query: {},
})
const paramsIndividual = ref({})
const showIndividualDetails = ref(false)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        row.receiptSumAmount = proxy.$fn.accMul(
          row.receiptPrice || 0,
          row.receiptCalcQty || 0
        )
      })
    }
    if (val.length && !tableInfo.value.isSysGroup) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )

        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  { deep: true }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const isUpdate = computed(() => {
  return formInfo.value.data.id !== undefined
})
const isReadOnly = computed(() => {
  //确定是否为提交状态
  return !formInfo.value.data.status === 1
})
const canAddProduct = computed(() => {
  return (
    formInfo.value.data.depotName &&
    formInfo.value.data.deptName &&
    formInfo.value.data.supplierName
  )
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.value.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.value.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.value.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function changeContract(row, index) {
  //打开切换合同弹窗
  if (!row.contractVOList) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '没有能切换的合同',
    })
    return
  }
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
  if (!contractInfo.value.data.length) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '没有能切换的合同',
    })
    return
  }
  //打开切换合同弹窗
  contractInfo.value.visible = true
  contractInfo.value.selectIndex = index
  contractInfo.value.changeContract = true
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
}
function selectContractCallBack(data) {
  if (data && data.id) {
    tableInfo.value.data[contractInfo.value.selectIndex]['quoteContractNo'] =
      data.orderNo
    tableInfo.value.data[contractInfo.value.selectIndex]['contractId'] = data.id
  } else {
    tableInfo.value.data[contractInfo.value.selectIndex]['quoteContractNo'] = ''
    tableInfo.value.data[contractInfo.value.selectIndex]['contractId'] = ''
  }
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function changeSwitch(e, num) {
  tableInfo.value.data.forEach((item, index) => {
    if (index === num) {
      item.largeUnitQty = e
        ? parseInt(item.stockAvailableCalcQty / item.unitConvertCoefficient)
        : 0
      item.smallUnitQty = e
        ? parseInt(item.stockAvailableCalcQty % item.unitConvertCoefficient)
        : 0
    }
  })
}
function ifRenderValue() {
  return tableInfo.value.isSysGroup
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.value.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  for (let key in individualInfo.value.selectObj) {
    individualInfo.value.selectObj[key].value = data[key]
  }
  if (props.purchReturnId) {
    individualInfo.value.leftQuery.isConsignBusiness = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: formInfo.value.data.isConsignBusiness,
    }
    individualInfo.value.rightQuery.isConsignBusiness = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: formInfo.value.data.isConsignBusiness,
    }
  }
  individualInfo.value.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatDepotStockIds,
  }
  individualInfo.value.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.value.leftQuery.depotId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.value.data.depotId,
  }
  individualInfo.value.leftQuery = {
    ...individualInfo.value.leftQuery,
    ...individualInfo.value.selectObj,
  }
  individualInfo.value.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  individualInfo.value.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.purchReturnId,
  }
  individualInfo.value.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    tableInfo.value.map.set(data.key, data)
    let index = tableInfo.value.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      tableInfo.value.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]
  let key = []
  tableInfo.value.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = mergeDetail[0][row.key]
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (tableInfo.value.map.has(newKey)) {
    if (
      oldInfo.groupConcatDepotStockIds.includes(detail.depotStockId.toString())
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = tableInfo.value.map.get(newKey)
        if (
          await value.groupConcatDepotStockIds.includes(
            detail.depotStockId.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}
function getUseReturnList() {
  if (!formInfo.value.data.depotId) {
    proxy.$message({
      message: '请选择仓库',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  if (!formInfo.value.data.deptId) {
    proxy.$message({
      message: '请选择部门',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  dialogInfo.value.visible = true
  dialogInfo.value.query.storageDepotId = formInfo.value.data.depotId
}
function selectOrderCallback(data) {
  if (data.length) {
    tableInfo.value.data = data.map((row) => {
      delete row.detailExtVOS
      return {
        ...row,
        id: null,
        qty: 0,
        stockQty: row.totalStockQty,
      }
    })
  }
}

function init() {
  getPurchReturnOrderDetail(props.purchReturnId).then((res) => {
    if (res) {
      formInfo.value.data = res.data
      tableInfo.value.data = res.data.details
    }
  })
}
function validateExpire(list = []) {
  let msg = ''
  let currentDate = moment().format('YYYY-MM-DD')
  list.forEach((item, index) => {
    if (!item.reason) {
      msg =
        msg + `第【${index + 1}】行产品【${item.commonName}】未选择退货原因<br>`
    }
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
function findFroduct(data) {
  const findItem = tableInfo.value.data.find(
    (item) =>
      item.productId === data.productId &&
      item.batchNumber === data.batchNumber &&
      item.validityDate === data.validityDate &&
      item.productionDate === data.productionDate
  )
  const param = {
    flag: !!findItem,
    item: findItem,
  }
  return param
}
async function onCallBackScanData(data, callback) {
  //扫码回调
  let { mergeDetail, detail } = data
  if (tableInfo.value.data && tableInfo.value.data.length) {
    let items = tableInfo.value.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatDepotStockIds)
        let bool = arr.includes(detail.depotStockId.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(row.stockAvailableCalcQty, row.calcQty)
          if (num <= 1) {
            return row.calcQty === row.stockAvailableCalcQty
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  let map = await proxy.$fn.getDepotStorage(
    mergeDetail,
    tableInfo.value.sysGroup,
    tableInfo.value.map,
    purchReturnDetailsCustomizeListAll,
    props.purchReturnId,
    individualInfo.value.rightVo
  )
  tableInfo.value.map = map
  tableInfo.value.data = [...map.values()]
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function openDepotWindow() {
  depotInfo.value.visible = true
}
function openSupplierWindow() {
  selectProductSupplier.value.visible = true
}
//切换供应商
function changeSupplier(row, index) {
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.productId = row.productId
  selectProductSupplier.value.query.supplierIdNotIn = row.supplierId
  index.value = index
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.value.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.value.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.value.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.value.query.depotId.value = formInfo.value.data.depotId
  selectDepotStorageInfo.value.query.supplierId.value =
    formInfo.value.data.supplierId
  selectDepotStorageInfo.value.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回
  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.value.sysGroup,
    tableInfo.value.map,
    purchReturnDetailsCustomizeListAll, //个体弹窗右边数据接口
    props.purchReturnId,
    individualInfo.value.rightVo //个体弹窗右边表格配置
  )
  tableInfo.value.map = map
  tableInfo.value.data = [...map.values()]
}
function getIdNotIn(data) {
  //获取选择产品列表时排除已选的id
  const productIds = data.map((item) => item.productId)
  let idNotIn = ''
  if (productIds.length) {
    const productIdsSet = new Set(productIds)
    idNotIn = [...productIdsSet].toString()
  }
  return idNotIn
}
//扫码条码
function onFocusInputScan() {
  setTimeout(() => {
    proxy.$refs.inputRefScan.focus()
    isActive.value = true
    document
      .getElementsByClassName('inputRefScanHidden')[0]
      .removeAttribute('readonly')
  }, 300)
}
function sumArr(arr) {
  let sum = 0
  arr.map((i) => {
    sum += Number(i.qty)
  })
  return sum
}
function addBatchNumber(row, index) {
  index.value = index
  batchNumberInfo.value.visible = true
  batchNumberInfo.value.query = {
    idNotIn: tableInfo.value.data
      .map((detail) => detail.depotStorageId)
      .join(','),
    depotId: formInfo.value.data.depotId,
    productId: row.productId,
  }
}

//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (item) => item.key !== row.key
    )
    let key = row.key
    tableInfo.value.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.selections.forEach((row) => {
          for (let [key, value] of tableInfo.value.map) {
            if (key === row.key) {
              tableInfo.value.map.delete(key)
            }
          }
        })
        tableInfo.value.data = tableInfo.value.data.filter((row) => {
          return !tableInfo.value.selections.includes(row)
        })
      })
  }
}
//选择产品回调
function selectProduct(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
        productId: item.id,
        supplierName: formInfo.value.data.supplierName,
        supplierId: formInfo.value.data.supplierId,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
//打开选择收货地址窗口
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.value.visible = true
}
function selectSupplierCallback(data) {
  if (data && data.supplierId) {
    formInfo.value.data['supplierId'] = data.supplierId
    formInfo.value.data['supplierName'] = data.supplierName
    formInfo.value.data['contact'] = data.contact
    formInfo.value.data['phone'] = data.phone
    scanInfo.value.query.queryParams.supplierId = data.supplierId
    tableInfo.value.data = []
  } else {
    formInfo.value.data['supplierId'] = ''
    formInfo.value.data['supplierName'] = ''
    formInfo.value.data['contact'] = ''
    formInfo.value.data['phone'] = ''
    tableInfo.value.data = []
  }
}

//打开部门弹窗
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
//选择仓库返回
function selectDepotCallBack(data = undefined) {
  if (data) {
    if (formInfo.value.data.depotId !== data.id) {
      formInfo.value.data.depotId = data.id
      formInfo.value.data.depotName = data.name
      formInfo.value.data.deptId = data.deptId
      formInfo.value.data.deptName = data.deptName
      scanInfo.value.query.queryParams.depotId = Number(data.id)
      tableInfo.value.data = []
    }
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptId = ''
    formInfo.value.data.deptName = ''
    scanInfo.value.query.queryParams.depotId = ''
    tableInfo.value.data = []
  }
}
function save() {
  tableInfo.value.data.map((item) => {
    let key = 'reason'
    if (item.details) {
      item.details.map((i) => {
        i[key] = item.reason
      })
    }
  })

  if (!tableInfo.value.data.length) {
    proxy.$message({
      message: '请选择产品',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let errMsg = []
  let receiptErr = []

  tableInfo.value.data.forEach((item) => {
    if (
      item.needBatchNumber === 1 &&
      (!item.batchNumber || !item.productionDate || !item.validityDate)
    ) {
      errMsg.push(item.commonName)
    }

    if (
      !(item.receiptPrice && item.receiptCalcQty && item.receiptNumber) &&
      (item.receiptPrice || item.receiptCalcQty || item.receiptNumber)
    ) {
      receiptErr.push(item.commonName)
    }
  })
  if (receiptErr && receiptErr.length) {
    proxy.$message.warning(
      '请输入产品' + String(receiptErr) + '的开票数量/开票单价/开票号'
    )
    return
  }
  if (errMsg.toString()) {
    proxy.$message({
      message: '请选择产品' + errMsg + '的批号效期！',
      type: 'error',
      duration: 3500,
      showClose: true,
    })
    return
  }
  tableInfo.value.data.forEach((item) => {
    if (!item.qty) {
      errMsg.push(item.commonName)
    }
  })
  errMsg = Array.from(new Set(errMsg))
  if (errMsg.toString()) {
    proxy.$message({
      message: '产品' + errMsg + '出库量小于0，请重新填写！',
      type: 'error',
      duration: 3500,
      showClose: true,
    })
    return
  }

  proxy.$fn.checkForm(formRefs.value).then(() => {
    getCoreSystemConfigAll().then((resp) => {
      if (resp && resp.success) {
        let find = resp.data.find(
          (item) => item.systemConfigCode === 'allow_expire_out'
        )
        if (find) {
          let expire = validateExpire(tableInfo.value.data)
          if (find.value === '1') {
            if (expire) {
              proxy
                .$confirm(expire + ',是否继续?', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  dangerouslyUseHTMLString: true,
                })
                .then(() => {
                  const details = tableInfo.value.data
                  const data = formInfo.value.data
                  data.mergeDetails = proxy.$fn.filterBlacklist(details)
                  const api = data.id
                    ? updatePurchReturnOrder
                    : createPurchReturnOrder
                  api(data).then((resp) => {
                    if (resp && resp.success) {
                      proxy.$emit('returnModify', true)
                      showDialog.value = false
                    }
                  })
                  return
                })
                .catch(() => {
                  return
                })
            } else {
              const details = tableInfo.value.data
              const data = formInfo.value.data
              data.mergeDetails = proxy.$fn.filterBlacklist(details)
              const api = data.id
                ? updatePurchReturnOrder
                : createPurchReturnOrder
              api(data).then((resp) => {
                if (resp && resp.success) {
                  proxy.$emit('returnModify', true)
                  showDialog.value = false
                }
              })
              return
            }
          } else {
            if (expire) {
              proxy.$alert(expire + '，不允许出库！', '操作提示', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
              })
              return
            } else {
              const details = tableInfo.value.data
              const data = formInfo.value.data
              data.mergeDetails = proxy.$fn.filterBlacklist(details)
              const api = data.id
                ? updatePurchReturnOrder
                : createPurchReturnOrder
              api(data).then((resp) => {
                if (resp && resp.success) {
                  proxy.$emit('returnModify', true)
                  showDialog.value = false
                }
              })
              return
            }
          }
        } else {
          const details = tableInfo.value.data
          const data = formInfo.value.data
          data.mergeDetails = proxy.$fn.filterBlacklist(details)
          const api = data.id ? updatePurchReturnOrder : createPurchReturnOrder
          api(data).then((resp) => {
            if (resp && resp.success) {
              proxy.$emit('returnModify', true)
              showDialog.value = false
            }
          })
        }
      }
    })
  })
}
function selectBatchNumberCallback(data) {
  if (data.length) {
    data = data.map((x) => {
      return { ...x, id: null, depotStorageId: x.id }
    })
    const tableData = [...tableInfo.value.data]
    let arr = _.differenceBy(data, tableData, 'depotStorageId')
    if (arr.length) {
      arr.forEach((item) => {
        index.value += 1
        let i = _.findIndex(tableData, function (o) {
          return o.productId === item.productId && !o.depotStorageId
        })
        if (i >= 0) {
          tableInfo.value.data.splice(i, 1, {
            ...item,
            id: null,
            depotStorageId: item.depotStorageId,
            qty: 0,
          })
        } else {
          tableInfo.value.data.splice(index.value, 0, {
            ...item,
            id: null,
            depotStorageId: item.depotStorageId,
            qty: 0,
          })
        }
      })
    }
  }
}

function individualCallback(data) {
  if (data) {
    tableInfo.value.data[index.value] = {
      ...tableInfo.value.data[index.value],
      qty: data.qty,
      details: [...data.details],
      sumPrice: data.sumPrice,
    }
  }
}
function checkBoxChange(val) {
  if (!val) {
    filterInfo.value.query.subCode = ''
  }
}
const purchAccording = ref(props.purchAccording)
function getMain() {
  detailPurchReturn(props.purchReturnId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      formInfo.value.data.returnType = String(resp.data.returnType)
      scanInfo.value.query.queryParams.depotId = resp.data.depotId
      scanInfo.value.query.queryParams.supplierId = resp.data.supplierId
      selectDepotStorageInfo.value.query.isConsignBusiness.value =
        resp.data.isConsignBusiness
      scanInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      if (resp.data.purchAccording) {
        purchAccording.value = resp.data.purchAccording
        selectDepotStorageInfo.value.query.queryParams['purchAccording'] =
          resp.data.purchAccording
        individualInfo.value.leftQueryParams['purchAccording'] =
          resp.data.purchAccording
        setPurchAccording()
      }
      if (
        !(
          resp.data.purchAccording == '2' ||
          proxy.$store.state.permission.systemConfig.purch_according == '2'
        )
      ) {
        tableInfo.value.fieldList.forEach((item) => {
          if (item.value === 'quoteContractNo') {
            item['hidden'] = true
          }
        })
        setBusinessDate()
      }
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.purchReturnId
  getList()
}
function getList() {
  //修改请求明细信息
  purchReturnDetailsCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      data.forEach((item) => {
        //将返回的数据变成Map形式
        let key = []
        if (tableInfo.value.sysGroup.length) {
          tableInfo.value.sysGroup.forEach((row) => {
            let obj = {}
            obj.columnName = row.columnName
            obj.asTbName = row.asTbName
            obj.value = item[row.key]
            key.push(obj)
          })
        }
        item.key = JSON.stringify(key)
        tableInfo.value.map.set(item.key, item)
        if (!tableInfo.value.isSysGroup) {
          item.groupConcatDepotStockIds = item.depotStockId.toString()
          item.groupSize = 1
          let row = proxy.$fn.deepClone(item)
          delete row.key
          row.details = [row]
        }
      })
      tableInfo.value.data = data
      tableInfo.value.data.map((item) => {
        item.reason = String(item.reason)
      })
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'purchPurchReturnModify-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
  }
  tableInfo.value.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      // tableInfo.value.fieldList = [
      //   {
      //     label: '开票号',
      //     value: 'receiptNumber',
      //     type: 'slot',
      //     show: false,
      //     hidden: false,
      //   },
      //   {
      //     label: '开票数量',
      //     value: 'receiptCalcQty',
      //     type: 'slot',
      //     show: false,
      //     hidden: false,
      //   },
      //   {
      //     label: '开票单价',
      //     value: 'receiptPrice',
      //     type: 'slot',
      //     permission: !proxy.$permission('purchReturn:price'),
      //     show: false,
      //     hidden: false,
      //   },
      //   {
      //     label: '开票金额',
      //     value: 'receiptSumAmount',
      //     type: 'column',
      //     formatter: proxy.$fn.TripartiteMethod,
      //     permission: !proxy.$permission('purchReturn:price'),
      //     show: false,
      //     hidden: false,
      //   },
      //   ...tableInfo.value.fieldList,
      // ]
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.value.isSysGroup = true
        }
      }

      filterInfo.value.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置
  let param = {
    tableKey:
      'productPurchReturnPageWithDepotStockLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.value.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'depotStockId',
        })
        obj['depotStockId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      scanInfo.value.query.customizeUserVO = data
      individualInfo.value.selectObj = obj
      tableInfo.value.sysGroup = arr
      if (props.purchReturnId) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'purchPurchReturnModifySingle-com.slip.spd.entity.vo.purch.PurchReturnDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.value.rightVo = res.data
    }
  })
}

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    // type: 'slot',
    hidden: true,
  },
  reasonValue: {
    label: '退货原因',
    value: 'reasonValue',
    asValue: 'reason',
    type: 'slot',
    show: false,
    hidden: true,
  },
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchReturn:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchReturn:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('purchReturn:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  receiptNumber: {
    label: '开票号',
    value: 'receiptNumber',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptCalcQty: {
    label: '开票数量',
    value: 'receiptCalcQty',
    type: 'slot',
    show: false,
    hidden: true,
  },
  receiptPrice: {
    label: '开票单价',
    value: 'receiptPrice',
    type: 'slot',
    permission: !proxy.$permission('purchReturn:price'),
    show: false,
    hidden: true,
  },
  receiptSumAmount: {
    label: '开票金额',
    value: 'receiptSumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchReturn:price'),
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.purchReturnId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
getCustomize()
getInvdividualRightCustomize()
setPurchAccording()
function setPurchAccording() {
  let _changeContract = _.find(tableInfo.value.handle.btList, [
    'label',
    '切换合同',
  ])
  _changeContract.show = false
  if (
    parseInt(props.purchAccording) === 2 ||
    parseInt(purchAccording.value) === 2
  ) {
    _changeContract.show = true
  }
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 100px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
</style>
